/*
 * Christopher Deckers (chrriis@nextencia.net)
 * http://www.nextencia.net
 *
 * See the file "readme.txt" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */
package swing;

import html.HtmlAdapter;
import html.HtmlTreeNode;
import html.MyString;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import lib.ConnectionWeb;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.jsoup.select.NodeVisitor;

import pojo.Website;

import swing.WebInformation;


import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeComponent;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;
import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserAdapter;
import chrriis.dj.nativeswing.swtimpl.components.WebBrowserEvent;

/**
 * @author Christopher Deckers
 */
public class WebsiteGUI extends JPanel {

     	 private static String link="www.vinabook.com";
         private JPanel infoPanel; 
         private JWebBrowser webBrowser;
         private JWebBrowser webBrowser2;
         private DefaultMutableTreeNode htmlNode=null;
         private static JTree tree;
         private static int isChoice=-1;
         private HtmlAdapter adapter= new HtmlAdapter();
         
   
         public WebsiteGUI(Website web) {
                	infoPanel =new WebInformation();
                    if(web!=null)
                    {
                    	this.link=web.getWebsite();
                        ((WebInformation) infoPanel).setWebInformation(web);
                    }
                    JPanel contentPane = new JPanel(new BorderLayout());
                    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    double width = screenSize.getWidth();
                    double height = screenSize.getHeight();
                   
                    infoPanel.setBorder(BorderFactory.createTitledBorder("Web Info"));
        
                    infoPanel.setPreferredSize(new Dimension(300,500));
                    ((WebInformation)infoPanel).setWebsiteGUI(this);
                    add(infoPanel,BorderLayout.LINE_START);
                    
                    
                    JPanel webBrowserPanel = new JPanel(new BorderLayout());
                    webBrowserPanel.setBorder(BorderFactory.createTitledBorder("Native Web Browser component"));
                    webBrowserPanel.setPreferredSize(new Dimension((int) width-320,400) );
                    webBrowser = new JWebBrowser();
                    webBrowser.setJavascriptEnabled(true);                
                    webBrowser.navigate(this.link);
                    //////////////////////Phan code firebug////////////
                    class MyWebBrowserApapter extends WebBrowserAdapter{
                        @Override
                        public void loadingProgressChanged(WebBrowserEvent e){
                                
                                if(webBrowser.getLoadingProgress() == 100){
                                        String jsBorder = "var elem, elemOriginalBorder;" +
                                        				  "function borderOn(e){" +
                                        				  "if(!e)e=event;" +
                                        				  "e = e.target || e.srcElement;" +
                                        				  "if(e && e.style){" +
                                        				  "elem = e;" +
                                        				  "elemOriginalBorder = e.style.border;" +
                                        				  "e.style.border = '2px solid red';" +
                                        				  "}" +
                                        				  "}" +
                                        				  "function borderOff(e){" +
                                        				  "if(elem){" +
                                        				  "elem.style.border = elemOriginalBorder;" +
                                        				  "}" +
                                        				  "}" +
                                        				  "document.onmouseover = borderOn;" +
                                        				  "document.onmouseout = borderOff;";
                                        String js = "var scriptElement = document.createElement('script');" +
                                        			"scriptElement.type = 'text/javascript';" +
                                        			"scriptElement.language = 'javascript';" +
                                        			"try{" +
                                                    "scriptElement.appendChild(document.createTextNode(\"" + jsBorder + "\"));" + 
                                                    "}catch(e){" +
                                                    "scriptElement.text = \"" + jsBorder + "\";" +
                                                    "}" +   
                                                    "document.getElementsByTagName(\"head\")[0].appendChild(scriptElement);" +
                                                    "return document.getElementsByTagName(\"head\")[0].innerHTML";
                                        System.out.println((String)webBrowser.executeJavascriptWithResult(js));
                                        
                                        
                                        //phan xu ly jtree
 
                                        String st2=getUrl();
                                        link=st2;
                                        
                                        adapter.setUrl(st2);
                                        DefaultMutableTreeNode tNode=adapter.getRoot();
                                        ((HtmlTree)tree).setRoot(tNode);
                                        String url=getUrl();
                                      
                                        
                                        
                                }       
                        }
                    }
                    	webBrowser.addWebBrowserListener(new MyWebBrowserApapter());
        
                    class MyMouseMotionAdapter extends MouseMotionAdapter{
                        int oldX = -1;
                        int oldY = -1;
                        
                        @Override
                        public void mouseMoved(MouseEvent e){
                        }
                        @Override
                        public void mouseDragged(MouseEvent e){
                        	
                        }
                    }
                    class MyMouseAdapter extends MouseAdapter{
                        @SuppressWarnings("deprecation")
                                @Override
                        public void mousePressed(MouseEvent e){
                                 //webBrowser.getNativeComponent().setEnabled(false);
                                 //webBrowser.getNativeComponent().setEnabled(true);
                        	if(isChoice!=-1)
                        	{
                        		String js = "var element = document.elementFromPoint(" + e.getX() + "," + e.getY() + ");" +                                                                                                
                                      "  return element.outerHTML;";
                               String st = (String)webBrowser.executeJavascriptWithResult(js);  
                               
    
                               String st2=getUrl();
                               
                               String st3=webBrowser.getHTMLContent();
                               Document doc=Jsoup.parse(st3);
                               Elements le=doc.getElementsByTag("div");
    
                              // adapter.setHtmlString(st3);
                               Writer out1;
                   			try {
                   				out1 = new BufferedWriter(new OutputStreamWriter(
                   						new FileOutputStream("E:\\demo.html",true),"UTF-8"));
                   				try {
                   					out1.write(st3);
                
                   					out1.close();
                   				} catch (IOException e1) {
                   					// TODO Auto-generated catch block
                   					e1.printStackTrace();
                   				}
                   				
                   			} catch (UnsupportedEncodingException e1) {
                   				// TODO Auto-generated catch block
                   				e1.printStackTrace();
                   			} catch (FileNotFoundException e1) {
                   				// TODO Auto-generated catch block
                   				e1.printStackTrace();
                   			}
                               
                               if(link.equals(st2)==false)
                               {
                            	   DefaultMutableTreeNode tNode=adapter.getRoot();
                                   ((HtmlTree)tree).setRoot(tNode);
                               }
                               MyString path=  adapter.getPath(st);
                               TreePath treepath=adapter.getTreePath(tree, path);
                               adapter.collapseTree(tree);
                               tree.expandPath(treepath);
                               tree.setSelectionPath(treepath);
                               tree.scrollPathToVisible(treepath);
                               isChoice=-1;
                        	}
                        	
                        	
                        }
                    }
                    // Add Mouse Listeners
                    webBrowser.getNativeComponent().addMouseListener(new MyMouseAdapter());
                    webBrowser.getNativeComponent().addMouseMotionListener(new MyMouseMotionAdapter());
                    ////////////////////////////////////////////////////////////
                    
                    webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
                    webBrowserPanel.setPreferredSize(new Dimension((int) width-320,(int) height-250) );
                    add(webBrowserPanel, BorderLayout.CENTER);
                    
                    // Create an area that shows the various input events the web browser can send.
                    JPanel southPanel = new JPanel(new BorderLayout());
                    southPanel.setBorder(BorderFactory.createTitledBorder("Html Tree"));
                   // adapter.setHtmlString(webBrowser.getHTMLContent());
                    this.tree = new HtmlTree(htmlNode);
                    
                    tree.addMouseListener ( new MouseAdapter ()
                    {
                        public void mousePressed ( MouseEvent e )
                        {
                            if ( SwingUtilities.isRightMouseButton ( e ) )
                            {
                                TreePath path = tree.getPathForLocation ( e.getX (), e.getY () );
                                Rectangle pathBounds = tree.getUI ().getPathBounds ( tree, path );
                                if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) )
                                {
                                    JPopupMenu menu = new JPopupMenu ();
                                    JMenuItem item=new JMenuItem ( "Copy");
                                    item.addActionListener(new ActionListener() {
                            			public void actionPerformed(ActionEvent e) {
                            				JOptionPane.showMessageDialog(null,"Bạn vừa copy thông tin thẻ");
                            				TreePath path=tree.getSelectionPath();
                            				String stclip="";
                            				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
                            				stclip=selectedNode.toString();
                            				int numend=stclip.indexOf(">");
                            				if(numend<stclip.length())
                            					stclip=stclip.substring(0,numend+1);
                            				
                            				if(selectedNode.isLeaf()==false)
                            				{
                            					stclip=stclip+"/";
                            					DefaultMutableTreeNode Nodecon = (DefaultMutableTreeNode) selectedNode.getChildAt(0);
                            					String stcon=Nodecon.toString();
                            					int num4=stcon.indexOf(">");
                            					stcon=stcon.substring(0,num4+1);		
                            					stclip=stclip+stcon;                    				
                            				}
                            				
                            				String xp=getXpath(path,selectedNode);
                            				stclip=xp+"$$"+stclip;
                            				
                            				Toolkit toolkit = Toolkit.getDefaultToolkit();
                            				Clipboard clipboard = toolkit.getSystemClipboard();
                            				StringSelection strSel = new StringSelection(stclip);
                            				clipboard.setContents(strSel, null);
                            				int tNum=0;
                            				switch(isChoice)
                            				{
                            					case 1:
                            						tNum=1;
                            						break;
                            					case 2:
                            						tNum=2;
                            						break;
                            					case 3:
                            						tNum=3;
                            						break;
                            					case 4:
                            						tNum=4;
                            						break;
                            					case 5:
                            						tNum=5;
                            						break;
                            					case 6:
                            						tNum=6;
                            						break;
                            					case 7:
                            						tNum=7;
                            						break;                    					                        				
                            				}
                            				((WebInformation)infoPanel).setInformation(tNum, stclip);
                            			}
                            		});
                                    menu.add (item );
                                    menu.show ( tree, pathBounds.x, pathBounds.y + pathBounds.height );
                                    
                                }
                            }
                        }
                    } );
                    JScrollPane scrollPane = new JScrollPane(tree);
                    
                    
                    scrollPane.setPreferredSize(new Dimension((int) width-20, 120));
                    southPanel.add(scrollPane);
                    add(southPanel, BorderLayout.PAGE_END);
                    

          }
  
  
        public void setInfomation(Website web)
        {
                ((WebInformation) infoPanel).setWebInformation(web);
        }
        public void setUrl(String url)
        {	
                webBrowser.navigate(url);
                webBrowser.updateUI();
        }

        public String getUrl(){
                	String js = "return document.URL;";
                	return (String)webBrowser.executeJavascriptWithResult(js);
        }
                

        public void setChoice(int n)
        {
        	this.isChoice=n;
        }
        
        public WebsiteGUI getWebsiteGUI()
        {
        	return this;
        }
        
        
        public String getXpath(TreePath t,DefaultMutableTreeNode node)
        {
        	String kq="";
        	int n = t.getPathCount();
        	String name="";
        	
        	TreeNode tn=(TreeNode)node;
        	for(int i=0;i<n;i++)
        	{
        		TreeNode parent=tn.getParent();
        		if(parent==null) 
        		{
        			String st=getname(tn.toString());
        			kq="/"+st+kq;
        			break;
        		}
        		int m = parent.getChildCount();
        		String pn=getname(parent.toString());
        		int dem =0;
        		int vt=parent.getIndex(tn);
        		String nn=getname(tn.toString());
        		for(int j=0;j<m;j++)
        		{
        			TreeNode con=parent.getChildAt(j);
        			String cn=getname(con.toString());
        			if(cn.equals(nn)) dem++;
        			if(j==vt) break;		        			
        		}
        		if(dem>1)
        		{
        			kq="/"+nn+"["+Integer.toString(dem)+"]"+kq;
        		}
        		else
        		{
        			kq="/"+nn+kq;
        		}
        		
        		tn= parent;
        	}
        	
			return kq;
        	
        }
        
        public String getname(String t)
        {
        	int n1=t.indexOf(">");
        	int n2=t.indexOf(" ");
        	String st="";
        	if(n2==-1||n2>n1)
        	{
        		st=t.substring(1,n1);
        	}
        	else
        	{
        		st=t.substring(1,n2);
        	}
        	return st;
        	
        }
}